/*
 * ---------------------------------------------------------------------
 * Copyright (c) 2014, 2015 All Right Reserved
 * This software is developed for study and improve coding skill ...
 *
 * Project:  Excellent Coding < EC >
 *
 * ecCQueue.h
 * This file for EC Cyc Queue <template>interface define .
 * Eamil:  epengao@126.com
 * Author: Peter Gao
 * Version: First initinal version.
 * --------------------------------------------------------------------
 */
#ifndef EC_CQUEUE_H
#define EC_CQUEUE_H

#include "ecBaseType.h"

#define CQUEUE_DEFAULT_SIZE    1024

namespace ec {

template<typename T>
class ecCQueue
{
public:
    ecCQueue(EC_U32 nSize = CQUEUE_DEFAULT_SIZE);
    virtual ~ecCQueue();
    virtual void ResetCQueue();
    virtual EC_U32 AddItemToTail(T* pInData);
    virtual EC_U32 DeleteItemFromHead(T* pOutData);

protected:
    EC_U32 m_nSize;
    EC_U32 m_nHead;
    EC_U32 m_nTail;
    EC_U32 m_nItemCount;
    T*     m_pDataItems;
};

template<typename T>
ecCQueue<T>::ecCQueue(
 EC_U32 nSize /*CQUEUE_DEFAULT_SIZE*/)
:m_nSize(nSize)
,m_nHead(0)
,m_nTail(0)
,m_nItemCount(0)
,m_pDataItems(EC_NULL)
{
    m_pDataItems = new T[m_nSize];
}

template<typename T>
ecCQueue<T>::~ecCQueue()
{
    if(m_pDataItems)
        delete []m_pDataItems;
}

template<typename T>
void ecCQueue<T>::ResetCQueue()
{
    m_nHead = 0;
    m_nTail = 0;
    m_nItemCount = 0;
}

template<typename T>
EC_U32 ecCQueue<T>::AddItemToTail(T* pInData)
{
    if((m_nItemCount >= m_nSize) || (EC_NULL == m_pDataItems))
        return EC_Err_Memory_Overflow;

    EC_U32 nPos = (m_nTail % m_nSize);
    m_pDataItems[nPos] = *pInData;
    m_nTail++;
    m_nItemCount++;
    return EC_Err_None;
}

template<typename T>
EC_U32 ecCQueue<T>::DeleteItemFromHead(T* pOutData)
{
    if((m_nItemCount == 0) || (EC_NULL == m_pDataItems))
        return EC_Err_Memory_Overflow;

    EC_U32 nPos = (m_nHead % m_nSize);
    *pOutData = m_pDataItems[nPos];
    m_nHead++;
    m_nItemCount--;
    return EC_Err_None;
}
} /* namespace ec */

#endif /* EC_CQUEUE_H */